#
#  Copyright 2022 The Open Islands Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
import os

from pyoi.constant import ComputingEngine, StorageEngine, QueueEngine
from pyoi.util import IdUtils
from pyoi.util.log_utils import getLogger

LOGGER = getLogger()


class RuntimeENV:
    # OI
    OI_PROJECT_ROOT = None
    OI_LOG_LEVEL = None
    OI_PROFILE_LOG_ENABLED = None

    # OI service
    WORKER_SERVICE_HOST = None
    WORKER_SERVICE_HTTP_PORT = None
    WORKER_SERVICE_GRPC_PORT = None
    COMPUTING_ENGINE = None
    STORAGE_ENGINE = None
    QUEUE_ENGINE = None

    # spark
    SPARK_HOME = None

    # task
    JOB_ID: str = None
    TASK_NAME: str = None
    TASK_VERSION: str = None
    ROLE: str = None
    NODE_ID: str = None
    TASK_ID: str = None
    SESSION_ID: str = None
    CONFIG_DIR: str = None
    LOG_DIR: str = None

    #
    PYTHONINTERPRETER = None
    PYTHON_VIRTUAL_ENV = None
    PYTHONPATH = None
    JAVA_HOME = None

    API_VERSION = "v1"

    HEADERS = {
        "Content-Type": "application/json",
        "Connection": "close",
        "service": "pyoi"
    }
    MAX_TIMESTAMP_INTERVAL = 60
    LOCAL_API_REQUEST_TIMEOUT = 60 * 1000  # ms
    HTTP_APP_KEY = ""
    HTTP_SECRET_KEY = ""
    deserialize_using_safe_module = False

    @classmethod
    def init(cls):
        cls.init_from_sys_env()
        cls.parsing_enum_env()
        cls.check_env()

    @classmethod
    def init_from_sys_env(cls):
        for k in cls.__dict__.keys():
            value = os.getenv(k, default=None)
            if value is not None:
                RuntimeENV.set_env(k, value)

    @classmethod
    def parsing_enum_env(cls):
        cls.COMPUTING_ENGINE = ComputingEngine[cls.COMPUTING_ENGINE]
        cls.STORAGE_ENGINE = StorageEngine[cls.STORAGE_ENGINE]
        cls.QUEUE_ENGINE = QueueEngine[cls.QUEUE_ENGINE]

    @classmethod
    def check_env(cls):
        assert cls.SESSION_ID == IdUtils.get_task_session_id(cls.TASK_ID, cls.ROLE, cls.NODE_ID)

    @classmethod
    def init_envs(cls, **kwargs):
        for k, v in kwargs.items():
            cls.set_env(k, v)

    @classmethod
    def set_env(cls, key, value):
        if hasattr(cls, key):
            if value is not None:
                setattr(cls, key, value)

    @classmethod
    def get_all(cls):
        configs = {}
        for k, v in cls.__dict__.items():
            if not callable(getattr(cls, k)) and not k.startswith("__") and not k.startswith("_"):
                configs[k] = v
        return configs

    @classmethod
    def get(cls, name):
        return getattr(cls, name) if hasattr(cls, name) else None
